package com.hd.trans.ui.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.hardware.Camera
import android.os.Bundle
import android.text.TextUtils
import android.transition.Slide
import android.util.Log
import android.view.Gravity
import android.view.Window
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.SeekBar
import androidx.core.view.ViewCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.TranslationUI
import com.hd.trans.binding.visible
import com.hd.trans.common.Constants
import com.hd.trans.databinding.ActivityCameraHomeBinding
import com.hd.trans.db.DataBaseMgr
import com.hd.trans.db.bean.FileTranslateRecord
import com.hd.trans.db.bean.HuDunLanguage
import com.hd.trans.db.bean.MediaItem
import com.hd.trans.db.bean.TransitionType
import com.hd.trans.files.aty.MediaAlbumActivity
import com.hd.trans.files.bean.MediaOptions
import com.hd.trans.files.bean.MimeType
import com.hd.trans.framework.dialog.LanguageDialog
import com.hd.trans.framework.dialog.LanguageDialogType
import com.hd.trans.homefun.EventCode
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.share.AudioTimeFormatUtil
import com.hd.trans.ui.base.LimitBaseActivity
import com.hd.trans.ui.listener.ScreenOrientationListener
import com.hd.trans.ui.model.PictureTransModel
import com.hd.trans.utils.CamParaUtil
import com.hd.trans.utils.FileUtilsKotlin.assetRes2File
import com.hd.trans.utils.HDToastUtil
import com.hd.trans.utils.ImageUtil
import com.hd.trans.utils.ImageUtils
import com.hd.trans.utils.PhotoFileUtil
import com.hd.trans.utils.ScreenUtil
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.TrackerForTrans
import java.io.File
import java.io.IOException
import java.io.InputStream

class CameraHomeActivity: LimitBaseActivity(), CameraClickListener {
    private var twoWay: Boolean = false
    private var screenOrientation: Int = 0
    private var isStopPreview: Boolean = false
    lateinit var mDataBinding: ActivityCameraHomeBinding
    lateinit var mDataModel: PictureTransModel
    private var ta1: TranslateAnimation? = null
    private var ta2: TranslateAnimation? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_camera_home
    }

    companion object {

        @JvmStatic
        var productId: Int = -1
        @JvmStatic
        var userId: String = ""

        @JvmStatic
        fun open(context: Context, listener: LimitUseListener? = null, options: Bundle? = null) {
            limitListener = listener
            val intent = Intent(context, CameraHomeActivity::class.java)
            context.startActivity(intent, options)
        }

        @JvmStatic
        fun open(
            context: Context,
            listener: LimitUseListener? = null,
            productId: Int,
            userId: String,
            options: Bundle? = null,
        ) {
            limitListener = listener
            this.productId = productId
            this.userId = userId
            val intent = Intent(context, CameraHomeActivity::class.java)
            context.startActivity(intent, options)
        }
    }

    private val screenOrientationListener by lazy {
        ScreenOrientationListener(this).apply {
            setOnOrientationChangedListener {
                if(it != 0 && it != 270){
                    return@setOnOrientationChangedListener
                }

                //结束动画ta1、ta2
                ta1?.cancel()
                ta2?.cancel()

                //反馈旋转角度
                screenOrientation = it

                /** 设置相机预览画面角度 */
                var rotation = (screenOrientation + 360 - 270) % 360
                val mCamera = mDataBinding.cameraPreview.getmCamera()
                if (null != mCamera) {
                    val parameters: Camera.Parameters = mCamera.parameters
                    parameters.setRotation(rotation)
                    Log.e("setRotation", "screenOrientation: $screenOrientation, rotation: $rotation")
                    mCamera.parameters = parameters
                }


                if(it == 270){
                    val screenWidth = ScreenUtil.getScreenWidth(this@CameraHomeActivity)
                    val screenHeight = ScreenUtil.getScreenHeight(this@CameraHomeActivity)
                    mDataBinding.tvTips.animate().translationX(250f/1080f*screenWidth)
                        .translationY(650f/2110f*screenHeight).duration = 300
                    mDataBinding.rlLang.animate().translationX(400f/1080f*screenWidth)
                        .translationY(920f/2110f*screenHeight).duration = 300
                }else if(it == 0){
                    mDataBinding.tvTips.animate().translationX(0f).translationY(0f).duration = 300
                    mDataBinding.rlLang.animate().translationX(0f).translationY(0f).duration = 300
                }
                //提示文案控件旋转
                //mDataBinding.flPictureAlbum.rotation = -1.0f * it.toFloat()
                //添加旋转动画
                val rotationOrientation = (360 - it.toFloat())%360
                mDataBinding.flPictureAlbum.animate().rotation(rotationOrientation).duration = 300
                mDataBinding.flTakePicture.animate().rotation(rotationOrientation).duration = 300
                mDataBinding.flPictureHistory.animate().rotation(rotationOrientation).duration = 300
                mDataBinding.ivFlashlight.animate().rotation(rotationOrientation).duration = 300
                mDataBinding.tvTips.animate().rotation(rotationOrientation).duration = 300
                mDataBinding.rlLang.animate().rotation(rotationOrientation).duration = 300

            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        window.requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
        super.onCreate(savedInstanceState)
    }

    override val pageType: EventCode
        get() = EventCode.CAMERA_TRANS

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        super.initViewsAndEvents(savedInstanceState)
        setStatusBarFontColor(false)
        //视图埋点
        TranslationInterior.getTrackerListener().view("${TrackerForTrans.PZFY}${TrackerForTrans.SY}")
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_camera_home)
        mDataModel = ViewModelProvider(this).get(PictureTransModel::class.java)

        initView()
        initData()
    }

    override fun onResume() {
        super.onResume()
        if(isStopPreview){
            isStopPreview = false
            mDataBinding.cameraPreview.startPreview()
        }
        screenOrientationListener.onResume()
    }

    override fun onPause() {
        super.onPause()
        screenOrientationListener.onPause()
        isStopPreview = true
        mDataBinding.cameraPreview.stopPreview()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataModel.languageFrom.removeObservers(this)
        mDataModel.languageTo.removeObservers(this)
    }

    private fun initView() {
        mDataBinding.run {
            clicks = this@CameraHomeActivity
            activity.window.enterTransition = Slide(Gravity.RIGHT)//Slide(Gravity.RIGHT)
            activity.window.exitTransition = Slide(Gravity.RIGHT)
            ViewCompat.setTransitionName(btnTakePicture, resources.getString(R.string.share_photo))

            setListeners()
            setWindowScreenBrightness(50)
            seekBarLight.progress = 50
            ivFlashlight.setImageLevel(Constants.LIGHT_AUTO)
        }
    }

    private fun setListeners(){
        mDataBinding.seekBarLight.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, "亮度调整")
                setWindowScreenBrightness(progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }

        })

        mDataBinding.seekBarSize.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, "焦距调整")
                setZoom(progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }

        })
    }

    private fun initData() {
        /**
         *  监听页面数据变化(语言改变，状态改变)
         */
        mDataModel.languageFrom.observe(this) { huDunLanguage: HuDunLanguage? ->
            if (huDunLanguage != null) {
                mDataBinding.tvFrom.text = huDunLanguage.name
            }
        }
        mDataModel.languageTo.observe(this) { huDunLanguage: HuDunLanguage? ->
            if (huDunLanguage != null) {
                dualIdentityLang(huDunLanguage)
                mDataBinding.tvTo.text = huDunLanguage.name
            }
        }

        val fromLangName = PreferenceMgr.getInstance().translatePreference.fileFromLanguage
        val toLangName = PreferenceMgr.getInstance().translatePreference.fileToLanguage
        mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName))
        mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName))

        if(limitListener == null || limitListener?.isAllowTransit(EventCode.CHECK_FUNCTION_SWITCH_A) == true){
            showExperiencedDialog()
        }
    }

    private fun showExperiencedDialog(){
        if(PreferenceMgr.getInstance().isExperienced) {
            mDataBinding.rlExample.visible = false
            if(isVip()){
                mDataBinding.rlExample2.visible = false
            }else if(!PreferenceMgr.getInstance().isExperiencedClose){
                //视图埋点
                TranslationInterior.getTrackerListener().view(TrackerForTrans.EXPERIENCE_SMALL_VIEW)
                mDataBinding.rlExample2.visible = true
            }
        }else{
            //视图埋点
            TranslationInterior.getTrackerListener().view(TrackerForTrans.EXPERIENCE_VIEW)
            mDataBinding.rlExample.visible = true

            //标记为已经体验了
            PreferenceMgr.getInstance().isExperienced = true
        }
    }

    private fun dualIdentityLang(toLang: HuDunLanguage){
        twoWay = if(!TextUtils.isEmpty(toLang.fileRecognitionCode)){
            mDataBinding.ivSwitch.setImageResource(R.mipmap.icon_change)
            true
        }else{
            mDataBinding.ivSwitch.setImageResource(R.mipmap.icon_trans_dx)
            false
        }
    }

    /**选择语言弹框*/
    private fun showSelectLanguageDialog(isFrom: Boolean) {
        /*val filterLangList = ArrayList<String>()
        filterLangList.add("藏语")
        SelectLanguageDialog.newInstance(
            mDataModel.languageFrom.value,
            mDataModel.languageTo.value,
            isFrom,
            false,
            false,
            filterLangList
        ).setOnLanguageChangedListener { language: HuDunLanguage?, isFrom: Boolean ->
            if (isFrom) {
                mDataModel.setLanguageFrom(language)
            } else {
                mDataModel.setLanguageTo(language)
            }
        }.show(supportFragmentManager, "TextHomeActivity")*/


        /*SelectLanguageDialog.newInstance(mDataModel.getLanguageFrom().getValue(), mDataModel.getLanguageTo().getValue(), isFromPage, false, isNation)
                .setOnLanguageChangedListener((language, isFrom) -> {
                    if (isFrom) {
                        mDataModel.setLanguageFrom(language);
                    } else {
                        mDataModel.setLanguageTo(language);
                    }
                }).show(getSupportFragmentManager(), "TextHomeActivity");*/
        val dialog = LanguageDialog(
            mDataModel.languageFrom.value!!,
            mDataModel.languageTo.value!!,
            isFrom, LanguageDialogType.FILE, LanguageDialogType.TO_FILE_FILTRATION)
        dialog.show(supportFragmentManager, "LanguageDialog")
        dialog.setOnLanguageChangedListener(object : LanguageDialog.OnLanguageChangedListener{
            override fun onLanguageChanged(
                fromLanguage: HuDunLanguage,
                toLanguage: HuDunLanguage,
                selectedLanguage: HuDunLanguage,
            ) {
                mDataModel.setLanguageFrom(fromLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveFileFromLanguage(fromLanguage.name)
                mDataModel.setLanguageTo(toLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveFileToLanguage(toLanguage.name)
            }

        })
    }

    /**
     * 互换语种动画
     */
    private fun showTranslateAnimation() {
        if(!twoWay){
            ToastUtils.showNormal("${mDataModel.languageTo.value?.name}暂不支持双向翻译")
            return
        }
        if ("自动检测" == mDataModel.languageFrom.value?.name) {
            return
        }
        ta1 = TranslateAnimation(0f, (mDataBinding.lyFrom.width + mDataBinding.ivSwitch.width).toFloat(), 0f, 0f).apply {
            duration = 600
            fillAfter = true
        }
        mDataBinding.lyFrom.startAnimation(ta1)
        mDataBinding.lyFrom.bringToFront()
        ta2 = TranslateAnimation(0f, (-mDataBinding.lyTo.width - mDataBinding.ivSwitch.width).toFloat(), 0f, 0f).apply {
            duration = 600
            fillAfter = true
        }
        mDataBinding.lyTo.startAnimation(ta2)
        mDataBinding.lyTo.bringToFront()
        ta1?.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                val fromTemp: HuDunLanguage? = mDataModel.languageFrom.value
                mDataModel.setLanguageFrom(mDataModel.languageTo.value)
                mDataModel.setLanguageTo(fromTemp)
                PreferenceMgr.getInstance().translatePreference.saveFileFromLanguage(mDataModel.languageFrom.value?.name)
                PreferenceMgr.getInstance().translatePreference.saveFileToLanguage(mDataModel.languageTo.value?.name)
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        ta2?.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
    }

    /**
     * 闪光灯切换
     */
    private fun changeLight() {
        var level: Int = mDataBinding.ivFlashlight.drawable.level
        level += 1
        val maxLens = 3
        if (level > maxLens) {
            level = 1
        }
        when (level) {
            Constants.LIGHT_AUTO -> CamParaUtil.turnAuto(mDataBinding.cameraPreview.getmCamera())
            Constants.LIGHT_ON -> CamParaUtil.turnOn(mDataBinding.cameraPreview.getmCamera())
            Constants.LIGHT_OFF -> CamParaUtil.turnoff(mDataBinding.cameraPreview.getmCamera())
        }
        mDataBinding.ivFlashlight.setImageLevel(level)
    }

    /**
     * 从相册中选择图片
     */
    private fun choosePhoto() {
//        Intent intent = new Intent("android.intent.action.GET_CONTENT");
//        intent.setType("image/*");
//        startActivityForResult(intent, REQUEST_CODE_CHOOSE);
        val options: MediaOptions = MediaOptions.build(100)
            .setMax(1)
            .setMin(1)
            .setMediaType(MediaOptions.TYPE_IMAGE)
            .setIncludeMimeType(MimeType.JPEG, MimeType.PNG, MimeType.HEIC)
        val intent = Intent(this, MediaAlbumActivity::class.java)
        intent.putExtra(MediaAlbumActivity.TAG_MEDIA_OPTIONS, options)
        startActivityForResult(intent, TransitionType.PHOTO)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == TransitionType.PHOTO && resultCode == RESULT_OK) {
            if (data?.hasExtra(MediaAlbumActivity.TAG_RESULT) == false) {
                return
            }
            val list: ArrayList<MediaItem>? = data?.getParcelableArrayListExtra(MediaAlbumActivity.TAG_RESULT)
            if (list?.size == 0) {
                return
            }
            list?.let {
                if(it.size > 0){
                    val filePath = list[0].path
                    if (!TextUtils.isEmpty(filePath)) {
                        var bm = BitmapFactory.decodeFile(filePath)
                        //                int degree = ImageUtil.readPictureDegree(filePath);
                        val degree: Int = ImageUtils.getExifOrientation(filePath)
                        if (degree != 0) { // 旋转照片角度
                            bm = ImageUtils.rotateBitmapByDegree(bm, degree)
                        }
                        /*if (bm != null && bm.width > bm.height) {
                            bm = ImageUtils.rotateBitmapByDegree(bm, 90)
                        }*/
                        processBitmap(bm, false)
                    }
                }
            }

        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 图片压缩处理
     */
    private fun processBitmap(mBitmap: Bitmap?, isExperienced: Boolean) {
        if(isExperienced){
            var fileTranslateRecord = DataBaseMgr.getInstance().getFileTranslateRecordByTime(PreferenceMgr.getInstance().exampleCreateTime)
            if(fileTranslateRecord == null){
                fileTranslateRecord = FileTranslateRecord()
                fileTranslateRecord.apply {
                    createTime = System.currentTimeMillis()
                    PreferenceMgr.getInstance().saveExampleCreateTime(createTime)
                    updateTime = createTime
                    fileName = "拍照翻译_${AudioTimeFormatUtil.formatCreateTime1(createTime)}"
                    textLanguageFrom = DataBaseMgr.getInstance().getLanguageByName("英语")
                    textLanguageTo = DataBaseMgr.getInstance().getLanguageByName("中文（简体）")
                    fileLanguageFrom = DataBaseMgr.getInstance().getLanguageByName("英语")
                    fileLanguageTo = DataBaseMgr.getInstance().getLanguageByName("中文（简体）")

//                val originPicture = PhotoFileUtil.getPhotoDownloadPath()+"example/file_origin_example.png"
//                val transPicture = PhotoFileUtil.getPhotoDownloadPath()+"example/file_trans_example.png"
//                val originTxt = PhotoFileUtil.getPhotoDownloadPath()+"example/file_origin_example.untrans"
//                val transTxt = PhotoFileUtil.getPhotoDownloadPath()+"example/file_trans_example.trans"
//                val inpaintedFile = PhotoFileUtil.getPhotoDownloadPath()+"example/file_inpainted_example.jpg"
//                val metaFile = PhotoFileUtil.getPhotoDownloadPath()+"example/file_trans_example.meta"
                    val filePaths = arrayListOf(
                        "file_origin_example.png",
                        "file_trans_example.png",
                        "file_origin_example.untrans",
                        "file_trans_example.trans",
                        "file_inpainted_example.jpg",
                        "file_trans_example.meta"
                    )

                    filePaths.forEach {
                        if(!File(PhotoFileUtil.getPhotoDownloadPath()+it).exists()){
                            assetRes2File(
                                assets,
                                "example/$it",
                                PhotoFileUtil.getPhotoDownloadPath()+it
                            )
                        }
                    }
                    originalFilePath = PhotoFileUtil.getPhotoDownloadPath()+filePaths[0]
                    translateFilePath = PhotoFileUtil.getPhotoDownloadPath()+filePaths[1]
                    originalText = PhotoFileUtil.getPhotoDownloadPath()+filePaths[2]
                    translateText = PhotoFileUtil.getPhotoDownloadPath()+filePaths[3]
                    inpaintedFilePath = PhotoFileUtil.getPhotoDownloadPath()+filePaths[4]
                    metaFilePath = PhotoFileUtil.getPhotoDownloadPath()+filePaths[5]
                }
                DataBaseMgr.getInstance().addFileTranslateRecord(fileTranslateRecord)
            }

            //执行图片翻译
            PictureTransResultActivity.open(
                this@CameraHomeActivity,
                null,
                fileTranslateRecord.createTime,
                productId,
                userId,
                limitListener)

            finish()
            return
        }

        if (mBitmap == null || mBitmap.width < 30) {
            runOnUiThread { HDToastUtil.show("图片尺寸太小或已损坏") }
            return
        }

        ImageUtil.processBitmap(mBitmap){
            if (!intercept(true)) {
                //执行图片翻译
                PictureTransResultActivity.open(
                    this@CameraHomeActivity,
                    it,
                    0,
                    productId,
                    userId,
                    limitListener)
                finish()
            }
        }
    }

    private fun getExampleBitmap(): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            val `is`: InputStream = activity.assets.open("example/file_origin_example.png")
            bitmap = BitmapFactory.decodeStream(`is`)
            `is`.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return bitmap
    }

    private fun checkPermissions(callback: () -> Unit) {
        val permissions = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE)
        val isIntercept = limitListener?.interceptPermission(this@CameraHomeActivity,
            EventCode.PERMISSION_STORAGE,
            permissions) {
            callback.invoke()
        }?:false
        if (!isIntercept) {
            //APP没有拦截，需要自己处理权限
            permissionUtil.checkIsHavePermission(this@CameraHomeActivity, permissions) {
                callback.invoke()
            }
        }
    }


    //修改当前Activity界面的窗口亮度，不影响其他Activity的亮度，退出恢复原本亮度
    private fun setWindowScreenBrightness(brightness: Int) {
        val lp = window.attributes
        lp.screenBrightness = brightness.toFloat() / 100.0f
        window.attributes = lp
    }

    private fun changeWindowScreenBrightness(value: Int){
        val lp = window.attributes
        var screenBrightness = lp.screenBrightness * 100.0f
        screenBrightness += value

        val result = if(screenBrightness > 100) 100f else if(screenBrightness < 0) 0f else screenBrightness
        lp.screenBrightness = result / 100.0f
        window.attributes = lp

        mDataBinding.seekBarLight.progress = result.toInt()
    }

    /**
     * 检测是否支持调节焦距
     */
    private fun isSupportZoom(camera: Camera): Boolean {
        var isSupport = true
        if (camera != null && camera.parameters.isSmoothZoomSupported) {
            isSupport = false
        }
        return isSupport
    }

    /**
     * 调节焦距
     */
    private fun changeZoom(value: Int) {
        val mCamera = mDataBinding.cameraPreview.getmCamera()
        mCamera?.let {camera ->
            if (isSupportZoom(camera)) {
                try {
                    val params = camera.parameters
                    val maxZoom: Int = params.maxZoom
                    if (maxZoom == 0) return
                    var zoomValue: Int = params.zoom
                    zoomValue += value

                    val result = if(zoomValue > maxZoom) maxZoom else if(zoomValue < 0) 0 else zoomValue
                    params.zoom = result
                    camera.parameters = params
                    mDataBinding.seekBarSize.progress = result
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            } else {
                Log.d("PhotoTransNewFragment","--------the phone not support zoom")
            }
        }
    }
    private fun setZoom(zoomValue: Int) {
        val mCamera = mDataBinding.cameraPreview.getmCamera()
        mCamera?.let { camera ->
            if (isSupportZoom(camera)) {
                try {
                    val params = camera.parameters
                    val maxZoom: Int = params.maxZoom
                    if (maxZoom == 0) return
                    params.zoom = if(zoomValue > maxZoom) maxZoom else zoomValue
                    camera.parameters = params
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            } else {
                Log.d("PhotoTransNewFragment","--------the phone not support zoom")
            }
        }
    }

    private fun getZoomValue(): Int {
        val mCamera = mDataBinding.cameraPreview.getmCamera()
        val params = mCamera?.parameters ?: return 0
        return params.zoom
    }

    private fun getMaxZoom(): Int{
        val mCamera = mDataBinding.cameraPreview.getmCamera()
        val params = mCamera?.parameters ?: return 100
        return params.maxZoom
    }

    override fun flashlight() {
        changeLight()
    }

    override fun back() {
        finish()
    }

    override fun takePicture() {
        if (!intercept(true)) {
            //埋点
            TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.TakePhoto)
            val orientation: Int = screenOrientation
            mDataBinding.cameraPreview.takePhoto { data, camera ->
                var mBitmap = BitmapFactory.decodeByteArray(data, 0, data.size)

                if(orientation == 0){//0表示竖屏拍照，一些手机自动选择角度问题
                    val info = Camera.CameraInfo()
                    Camera.getCameraInfo(0, info) //得到Camera相机信息

                    mBitmap = if (mBitmap.width < mBitmap.height) { //解决自动旋转却不记录旋转角度的问题
                        val bitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.width, mBitmap.height)
                        if (bitmap != mBitmap) {
                            mBitmap.recycle()
                        }
                        bitmap
                    } else {
                        ImageUtils.rotateBitmapByDegree(mBitmap, info.orientation)
                    }
                }

                processBitmap(mBitmap, false)
            }
        }
    }

    override fun toHistory() {
        //埋点
        TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.History)
        TranslationUI.openCameraTransHistoryActivity(this, limitListener)
    }

    override fun toAlbum() {
        checkPermissions {
            //埋点
            TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.AlbumUpload)
            choosePhoto()
        }
    }

    override fun fromLang() {
        showSelectLanguageDialog(true)
    }

    override fun toLang() {
        showSelectLanguageDialog(false)
    }

    override fun switchLang() {
        showTranslateAnimation()
    }

    override fun experience() {
        if(mDataBinding.rlExample.visible){
            //埋点
            TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.EXPERIENCE_VIEW)
            mDataBinding.rlExample.visible = false
        }
        if(mDataBinding.rlExample2.visible){
            //埋点
            TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.EXPERIENCE_SMALL_VIEW)
        }
        PreferenceMgr.getInstance().translatePreference.saveTansFromLanguage("英语")
        PreferenceMgr.getInstance().translatePreference.saveTansToLanguage("中文（简体）")
        val bitmap = getExampleBitmap()
        processBitmap(bitmap,true)
    }

    override fun closeExample() {
        if(mDataBinding.rlExample.visible){
            mDataBinding.rlExample.visible = false
        }
        if(mDataBinding.rlExample2.visible){
            PreferenceMgr.getInstance().isExperiencedClose = true
            mDataBinding.rlExample2.visible = false
        }
    }

    override fun brightnessDown() {
        changeWindowScreenBrightness(-10)
    }

    override fun brightnessUp() {
        changeWindowScreenBrightness(10)
    }

    override fun sizeDown() {
        changeZoom(-10)
    }

    override fun sizeUp() {
        changeZoom(10)
    }
}

interface CameraClickListener{
    fun flashlight()
    fun back()
    fun takePicture()
    fun toHistory()
    fun toAlbum()
    fun fromLang()
    fun toLang()
    fun switchLang()
    fun experience()
    fun closeExample()
    fun brightnessDown()
    fun brightnessUp()
    fun sizeDown()
    fun sizeUp()
}